package com.vimi8.ebb.api.ebb;

import com.vimi8.ebb.configuration.HttpResponseEntity;
import com.vimi8.ebb.configuration.OAuth2AuthenticationImpl;
import com.vimi8.ebb.dto.*;
import com.vimi8.ebb.manage.ElectricityBusinessManageImpl;
import com.vimi8.ebb.model.*;
import com.vimi8.ebb.model.Error;
import com.vimi8.ebb.service.ElectricityBusinessService;
import com.vimi8.ebb.service.EnumCategoryService;
import com.vimi8.ebb.service.GeoCodingsService;
import com.vimi8.ebb.service.PorductInfoService;
import com.vimi8.ebb.util.CommonUtil;
import com.vimi8.ebb.util.JxlExcelUtil;
import com.vimi8.ebb.util.PagesUtil;
import com.vimi8.ebb.util.SubStringUtil;
import io.swagger.annotations.ApiParam;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by wangyang on 2017/1/19.
 */
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringCodegen", date = "2016-09-19T10:01:46.405Z")

@Controller
public class ElectricityBusinessController implements ElectricityBusinessApi {
    private static final Logger logger = LoggerFactory.getLogger(ElectricityBusinessController.class);
    @Autowired
    private ElectricityBusinessService electricityBusinessService;
    @Autowired
    private ElectricityBusinessManageImpl electricityBusinessManage;
    @Autowired
    private GeoCodingsService geoCodingsService;
    @Autowired
    private EnumCategoryService enumCategoryService;
    @Autowired
    private PorductInfoService porductInfoService;
    @Value("${springfox.documentation.swagger.v2.host}")
    private String host;
    @Value("${server.port}")
    private String port;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public HttpResponseEntity<String> registerElectricityBusiness(HttpServletRequest request,@ApiParam(value = "电商信息.", required = true) @RequestBody ElectricityBusiness electricityBusiness) {
        // electricityBusiness.setId(UUID.randomUUID().toString());
        List<ElectricityBusiness> electricityBusinessList=new ArrayList<>();
        electricityBusiness.setId(UUID.randomUUID().toString());
        electricityBusinessList.add(electricityBusiness);
        if(!StringUtils.isEmpty(electricityBusiness)&&"-1".equals(electricityBusiness.getPlatformCategory())){
            electricityBusiness.setPlatformCategory(null);
        }
        String addressCode=  electricityBusinessService.getClientAddressCode(OAuth2AuthenticationImpl.openId());
        electricityBusiness.setAddressCode(addressCode);
        String url= request.getScheme() + "://" + host + ":" + port + "/auth/org/corp/batch/" ;
        try {
            String result = electricityBusinessManage.registerElectricityBusiness(electricityBusinessList,url);
           // redisTemplate.delete("/admin/ebb/list/-*");
            Set<String> keys = redisTemplate.keys("/admin/ebb/list/-" + "*");
            redisTemplate.delete(keys);
            Set<String> keys1 = redisTemplate.keys("/ebb/list/-" + "*");
            redisTemplate.delete(keys1);
            return new HttpResponseEntity<String>(result, HttpStatus.OK);
        }catch (Exception e){
            return new HttpResponseEntity<String>(e.getMessage(),HttpStatus.SERVICE_UNAVAILABLE);
        }
    }

    @Override
    public HttpResponseEntity<Paginator<List<ElectricityBusinessDto>>> getElectricityBusinessList(
            @ApiParam(value = "页码", required = true) @RequestParam(value = "start", required = true) int start,
            @ApiParam(value = "数据大小", required = true) @RequestParam(value = "size", required = true) int size,
            @ApiParam(value = "电商类型(1:第三方平台2:电商平台3:自建平台)", required = true) @RequestParam(value = "type",required = true) String type,
            @ApiParam(value = "地址码", required = false) @RequestParam(value = "addressCode",required = false) String addressCode,
            @ApiParam(value = "开始时间", required = false) @RequestParam(value = "startTime",required = false) String startTime,
            @ApiParam(value = "结束时间", required = false) @RequestParam(value = "endTime",required = false) String endTime,
            @ApiParam(value = "电商名称", required = false) @RequestParam(value = "storeName",required = false) String  storeName) {
        try {
            String key="/ebb/list/-"+start+"-"+size+"-"+type+"-"+storeName+"-"+addressCode+"-"+startTime+"_"+endTime+"-";
            String code=null;
            int count=0;
            List<ElectricityBusinessDto> electricityBusinessDtoList=null;
            String orgClass = OAuth2AuthenticationImpl.ClientOrgClass();
            logger.info("addressCode:"+addressCode);
            String clientAddressCode = electricityBusinessService.getClientAddressCode(OAuth2AuthenticationImpl.openId());
            if ("org_ebb_county".equals(orgClass)) {
                addressCode=clientAddressCode;
            }
            logger.info("addressCode1:"+addressCode);
            PagesUtil pagesUtil=new PagesUtil();
            pagesUtil.setPageSize(size);
            pagesUtil.setCurrentPage(start);
            if(start<1){
                pagesUtil.setCurrentPage(1);
            }
            if (null!=addressCode&&!"".equals(addressCode)/*&&!"520600000000".equals(addressCode)*/){
                GeoCodings geoCodings=geoCodingsService.getGeoCodingsById(addressCode);
                code= SubStringUtil.separateGeoCodeByProduct(addressCode,geoCodings.getRegionLever()+1+"");
                logger.info("~~~~~~~~~~~~~~~~~~~~~~~code is:"+code);
            }else{
                code=addressCode;
            }

//            //如果结束时间不为空为空  则表示是TOP10页面表格数据
//            if(StringUtils.isEmpty(endTime)){
//                count =electricityBusinessService.getElectricityBusinessCountByType(type,storeName,code,startTime);
//                pagesUtil.setTotalCount(count);
//                electricityBusinessDtoList=electricityBusinessService.getElectricityBusinessList(type, storeName,code,startTime,
//                        pagesUtil.getStartPage(),size);
//            }else{
//                count =electricityBusinessService.getElectricityBusinessCountByType1(type,storeName,code,startTime,endTime);
//                pagesUtil.setTotalCount(count);
//                electricityBusinessDtoList=electricityBusinessService.getElectricityBusinessList1(type, storeName,code,startTime,endTime,
//                        pagesUtil.getStartPage(),size);
//            }

            String paginatorCache= (String) redisTemplate.opsForValue().get(key);
            if(!StringUtils.isEmpty(paginatorCache)){
                return new HttpResponseEntity(paginatorCache,HttpStatus.OK);
            }

            //判断如果电商服务站  则在交易详情表查交易额  否则在产品查
            if(!"2".equals(type)){
                //如果结束时间为空  则表示不是TOP10页面表格数据
                if(StringUtils.isEmpty(endTime)){
                    count =electricityBusinessService.getElectricityBusinessCountByType(type,storeName,code,startTime);
                    pagesUtil.setTotalCount(count);
                    electricityBusinessDtoList=electricityBusinessService.getElectricityBusinessList(type, storeName,code,startTime,
                            pagesUtil.getStartPage(),size);
                }else{
                    count =electricityBusinessService.getElectricityBusinessCountByType1(type,storeName,code,startTime,endTime);
                    pagesUtil.setTotalCount(count);
                    electricityBusinessDtoList=electricityBusinessService.getElectricityBusinessList1(type, storeName,code,startTime,endTime,
                            pagesUtil.getStartPage(),size);
                }
            }else{
                //如果结束时间为空  则表示不是TOP10页面表格数据
                if(StringUtils.isEmpty(endTime)){
                    count =electricityBusinessService.getStoreElectricityBusinessCountByType(type,storeName,code,startTime);
                    pagesUtil.setTotalCount(count);
                    electricityBusinessDtoList=electricityBusinessService.getStoreElectricityBusinessList(type, storeName,code,startTime,
                            pagesUtil.getStartPage(),size);
                }else{
                    count =electricityBusinessService.getStoreElectricityBusinessCountByType1(type,storeName,code,startTime,endTime);
                    pagesUtil.setTotalCount(count);
                    electricityBusinessDtoList=electricityBusinessService.getStoreElectricityBusinessList1(type, storeName,code,startTime,endTime,
                            pagesUtil.getStartPage(),size);
                }
//
//                for(ElectricityBusinessDto electricityBusinessDto:electricityBusinessDtoList){
//                      HashMap<String,Object> hashMap  = electricityBusinessService.getBusinessAndTrandingByEleId(electricityBusinessDto.getId());
//                      if(hashMap!=null){
//                            electricityBusinessDto.setBusinessVolume(hashMap.get("businessVolume").toString());
//                            electricityBusinessDto.setTradingVolume(hashMap.get("tradingVolume").toString());
//                      }
//                }
            }
            for (ElectricityBusinessDto electricityBusinessDto:electricityBusinessDtoList){
                //判断归属平台
                if(electricityBusinessDto.getPlatformCategoryParent()==1){
                    electricityBusinessDto.setPlatformCategoryParents("网络零售平台");
                }else{
                    electricityBusinessDto.setPlatformCategoryParents("本地生活类服务平台");
                }
                if(!StringUtils.isEmpty(electricityBusinessDto.getAddressCode())){
                    String addressCodes = geoCodingsService.getAddressWhole(electricityBusinessDto.getAddressCode());
                    electricityBusinessDto.setAddressCode(addressCodes);
                }
                if(electricityBusinessDto.getMobileNo()==null||"null".equalsIgnoreCase(electricityBusinessDto.getMobileNo())){
                    electricityBusinessDto.setMobileNo("");
                }
                if(electricityBusinessDto.getResponsiblePerson()==null||"null".equalsIgnoreCase(electricityBusinessDto.getResponsiblePerson())){
                    electricityBusinessDto.setResponsiblePerson("");
                }
            }

            Paginator<List<ElectricityBusinessDto>> paginator=new Paginator<List<ElectricityBusinessDto>>(pagesUtil.getCurrentPage(),pagesUtil.getPageSize(),pagesUtil.getTotalPage(),
                    pagesUtil.getTotalCount(),electricityBusinessDtoList);
            redisTemplate.opsForValue().set(key, JSONObject.fromObject(paginator).toString());
            return new HttpResponseEntity<Paginator<List<ElectricityBusinessDto>>>(paginator,HttpStatus.OK);
        }catch (Exception e){
            return new HttpResponseEntity(new Error().error("sql error").errorDescription(e.getMessage()),HttpStatus.SERVICE_UNAVAILABLE);
        }

    }

    @Override
    public HttpResponseEntity<HashMap<String, Object>> TransactionTotalAmount(
            @ApiParam(value = "电商类型", required = true) @RequestParam(value = "type", required = true) String type,
            @ApiParam(value = "地址码", required = false) @RequestParam(value = "addressCode", required = false) String addressCode,
            @ApiParam(value = "是否可爬取(-1:无法爬取，0:待验证是否可爬取，1:可爬取)", required = false) @RequestParam(value = "pick", required = false) String pick,
            @ApiParam(value = "开始时间", required = false) @RequestParam(value = "startTime", required = false) String startTime,
            @ApiParam(value = "结束时间", required = false) @RequestParam(value = "endTime", required = false) String endTime,
            @ApiParam(value = "电商名称", required = false) @RequestParam(value = "storeName", required = false) String storeName) {
        try{
            String code=null;
            String orgClass = OAuth2AuthenticationImpl.ClientOrgClass();

            String clientAddressCode = electricityBusinessService.getClientAddressCode(OAuth2AuthenticationImpl.openId());
            if ("org_ebb_county".equals(orgClass)) {
                addressCode=clientAddressCode;
            }
            HashMap<String,Object> map=new HashMap<>();
            if (null!=addressCode&&!"".equals(addressCode)){
                GeoCodings geoCodings=geoCodingsService.getGeoCodingsById(addressCode);
                code= SubStringUtil.separateGeoCodeByProduct(addressCode,geoCodings.getRegionLever()+1+"");
            }else{
                code=addressCode;
            }
            logger.info("gouride :"+code);
            if(!"2".equals(type)&&!"4".equals(type)){
                map=electricityBusinessService.getElectricityBusinessTransactionAmountAdmin(type, storeName,code,pick,startTime,endTime);
            }else{
                map=electricityBusinessService.getStoreElectricityBusinessTransactionAmountAdmin(type, storeName,code,pick,startTime,endTime);
            }
            return new HttpResponseEntity<HashMap<String, Object>>(map,HttpStatus.OK);
        }catch (Exception e){
            return new HttpResponseEntity(new Error().error("error!").errorDescription(e.getMessage()),HttpStatus.SERVICE_UNAVAILABLE);
        }

    }




    @Override
    public HttpResponseEntity<Integer> getUnPickAmountAdmin(
            @ApiParam(value = "电商类型", required = true) @RequestParam(value = "type", required = true) String type,
            @ApiParam(value = "地址码", required = false) @RequestParam(value = "addressCode", required = false) String addressCode,
            @ApiParam(value = "开始时间", required = false) @RequestParam(value = "startTime", required = false) String startTime,
            @ApiParam(value = "结束时间", required = false) @RequestParam(value = "endTime", required = false) String endTime,
            @ApiParam(value = "电商名称", required = false) @RequestParam(value = "storeName", required = false) String storeName) {
        try{
            String code=null;
            String orgClass = OAuth2AuthenticationImpl.ClientOrgClass();

            String clientAddressCode = electricityBusinessService.getClientAddressCode(OAuth2AuthenticationImpl.openId());
            if ("org_ebb_county".equals(orgClass)) {
                addressCode=clientAddressCode;
            }
            int count=0;
            if (null!=addressCode&&!"".equals(addressCode)){
                GeoCodings geoCodings=geoCodingsService.getGeoCodingsById(addressCode);
                code= SubStringUtil.separateGeoCodeByProduct(addressCode,geoCodings.getRegionLever()+1+"");
            }else{
                code=addressCode;
            }
            if(!"2".equals(type)&&!"4".equals(type)){
                count=electricityBusinessService.getUnPickAmountAdmin(type, storeName,code,startTime,endTime);
            }else{
                count=electricityBusinessService.getStoreUnPickAmountAdminAmountAdmin(type,storeName,code,startTime,endTime);
            }
            return new HttpResponseEntity<Integer>(count,HttpStatus.OK);
        }catch (Exception e){
            return new HttpResponseEntity(new Error().error("error!").errorDescription(e.getMessage()),HttpStatus.SERVICE_UNAVAILABLE);
        }

    }




    /**
     * 因为后台列表要按时间排序 所以另起炉灶
     * @param start
     * @param size
     * @param type
     * @param addressCode
     * @param startTime
     * @param endTime
     * @param storeName
     * @return
     */
    @Override
    public HttpResponseEntity<Paginator<List<ElectricityBusinessDto>>> getElectricityBusinessListAdmin(
            @ApiParam(value = "页码", required = true) @RequestParam(value = "start", required = true) int start,
            @ApiParam(value = "数据大小", required = true) @RequestParam(value = "size", required = true) int size,
            @ApiParam(value = "电商类型", required = true) @RequestParam(value = "type", required = true) String type,
            @ApiParam(value = "归属平台", required = false) @RequestParam(value = "platformCategory",required = false) String platformCategory,
            @ApiParam(value = "是否可爬取(-1:无法爬取，0:待验证是否可爬取，1:可爬取)", required = false) @RequestParam(value = "pick", required = false) String pick,
            @ApiParam(value = "地址码", required = false) @RequestParam(value = "addressCode", required = false) String addressCode,
            @ApiParam(value = "开始时间", required = false) @RequestParam(value = "startTime", required = false) String startTime,
            @ApiParam(value = "结束时间", required = false) @RequestParam(value = "endTime", required = false) String endTime,
            @ApiParam(value = "电商名称", required = false) @RequestParam(value = "storeName", required = false) String storeName) {

        logger.info("platformCategory:"+platformCategory);
        try {
            String code=null;
            int count=0;
            List<ElectricityBusinessDto> electricityBusinessDtoList=new ArrayList<>();
            String orgClass = OAuth2AuthenticationImpl.ClientOrgClass();

            String clientAddressCode = electricityBusinessService.getClientAddressCode(OAuth2AuthenticationImpl.openId());
            if ("org_ebb_county".equals(orgClass)) {
                addressCode=clientAddressCode;
            }
            PagesUtil pagesUtil=new PagesUtil();
            pagesUtil.setPageSize(size);
            if(start<1){
                pagesUtil.setCurrentPage(1);
            }
            pagesUtil.setCurrentPage(start);
            logger.info("addressCode="+addressCode);
            //如果传的的是铜仁市的addresscode则表示 ‘无对应区县’
            String cacheCode="";
            if (null!=addressCode&&!"".equals(addressCode)&&!"520600000000".equals(addressCode)){
                GeoCodings geoCodings=geoCodingsService.getGeoCodingsById(addressCode);
                code= SubStringUtil.separateGeoCodeByProduct(addressCode,geoCodings.getRegionLever()+1+"");
                cacheCode=code;
                logger.info("~~~~~~~~~~~~~~~~~~~~~~~code is:"+code);
            }else{
                code=addressCode;
                cacheCode=addressCode+"-no-"+UUID.randomUUID().toString();

            }
            StringBuilder timeSb=new StringBuilder();

            String key="/admin/ebb/list/-"+start+"-"+size+"-"+type+"-"+storeName+"-"+cacheCode+"-"+platformCategory+"_"+pick+"-";

            if(!StringUtils.isEmpty(startTime)){
                timeSb.append(startTime.replace("-",""));

            }
            if(!StringUtils.isEmpty(endTime)){
                timeSb.append(endTime.replace("-",""));
            }
            key=key+timeSb.toString();
            String paginatorCache= (String) redisTemplate.opsForValue().get(key);
            logger.info("paginatorCache="+paginatorCache);
            if(!StringUtils.isEmpty(paginatorCache)){
                return new HttpResponseEntity(paginatorCache,HttpStatus.OK);
            }

            logger.info("code="+code);
//            //如果结束时间不为空为空  则表示是TOP10页面表格数据
//            if(StringUtils.isEmpty(endTime)){
//                count =electricityBusinessService.getElectricityBusinessCountByType(type,storeName,code,startTime);
//                pagesUtil.setTotalCount(count);
//                electricityBusinessDtoList=electricityBusinessService.getElectricityBusinessList(type, storeName,code,startTime,
//                        pagesUtil.getStartPage(),size);
//            }else{
//                count =electricityBusinessService.getElectricityBusinessCountByType1(type,storeName,code,startTime,endTime);
//                pagesUtil.setTotalCount(count);
//                electricityBusinessDtoList=electricityBusinessService.getElectricityBusinessList1(type, storeName,code,startTime,endTime,
//                        pagesUtil.getStartPage(),size);
//            }

            //判断如果电商服务站  则在交易详情表查交易额  否则在产品查
            if(!"2".equals(type)&&!"4".equals(type)){

                count =electricityBusinessService.getElectricityBusinessCountByTypeByAdmin(type,storeName,code,pick,platformCategory
                        ,startTime,endTime);
                pagesUtil.setTotalCount(count);
                electricityBusinessDtoList=electricityBusinessService.getElectricityBusinessListAdmin(type, storeName,code,pick,platformCategory,startTime,endTime,
                        pagesUtil.getStartPage(),size);
            }else{

                count = electricityBusinessService.getStoreElectricityBusinessCountByTypeByAdmin(type,storeName,code,pick,platformCategory,startTime,endTime);
                pagesUtil.setTotalCount(count);
                electricityBusinessDtoList=electricityBusinessService.getStoreElectricityBusinessListAdmin(type, storeName,
                        code,pick,platformCategory,startTime,endTime,pagesUtil.getStartPage(),size);

//
//                for(ElectricityBusinessDto electricityBusinessDto:electricityBusinessDtoList){
//                      HashMap<String,Object> hashMap  = electricityBusinessService.getBusinessAndTrandingByEleId(electricityBusinessDto.getId());
//                      if(hashMap!=null){
//                            electricityBusinessDto.setBusinessVolume(hashMap.get("businessVolume").toString());
//                            electricityBusinessDto.setTradingVolume(hashMap.get("tradingVolume").toString());
//                      }
//                }
            }
            for (ElectricityBusinessDto electricityBusinessDto:electricityBusinessDtoList){
                if(!StringUtils.isEmpty(electricityBusinessDto.getAddressCode())){
                    String addressCodes = geoCodingsService.getAddressWhole(electricityBusinessDto.getAddressCode());
                    electricityBusinessDto.setAddressCode(addressCodes);
                }
                if(electricityBusinessDto.getMobileNo()==null||"null".equalsIgnoreCase(electricityBusinessDto.getMobileNo())){
                    electricityBusinessDto.setMobileNo("");
                }
                if(electricityBusinessDto.getResponsiblePerson()==null||"null".equalsIgnoreCase(electricityBusinessDto.getResponsiblePerson())){
                    electricityBusinessDto.setResponsiblePerson("");
                }
            }

            Paginator<List<ElectricityBusinessDto>> paginator=new Paginator<List<ElectricityBusinessDto>>(pagesUtil.getCurrentPage(),pagesUtil.getPageSize(),pagesUtil.getTotalPage(),
                    pagesUtil.getTotalCount(),electricityBusinessDtoList);
            redisTemplate.opsForValue().set(key, JSONObject.fromObject(paginator).toString());
            return new HttpResponseEntity<Paginator<List<ElectricityBusinessDto>>>(paginator,HttpStatus.OK);
        }catch (Exception e){
            return new HttpResponseEntity(new Error().error("sql error").errorDescription(e.getMessage()),HttpStatus.SERVICE_UNAVAILABLE);
        }
    }

    @Override
    public HttpResponseEntity<Paginator<List<ElectricityBusinessDto>>> getElectricityBusinessNoRegionListAdmin(
            @ApiParam(value = "页码", required = true) @RequestParam(value = "start", required = true) int start,
            @ApiParam(value = "数据大小", required = true) @RequestParam(value = "size", required = true) int size,
            @ApiParam(value = "电商类型", required = true) @RequestParam(value = "type", required = true) String type,
            @ApiParam(value = "地址码", required = true) @RequestParam(value = "addressCode", required = true) String addressCode) {
        try {
            String code=null;
            int count=0;
            List<ElectricityBusinessDto> electricityBusinessDtoList=new ArrayList<>();
            PagesUtil pagesUtil=new PagesUtil();
            pagesUtil.setPageSize(size);
            if(start<1){
                pagesUtil.setCurrentPage(1);
            }
            pagesUtil.setCurrentPage(start);

            //如果传的的是铜仁市的addresscode则表示 ‘无对应区县’
            String cacheCode="";
            cacheCode=addressCode+"-no";
            //String key="/admin/ebb/noRegionList/-"+start+"-"+size+"-"+type+"-"+cacheCode+"-";

            //String paginatorCache= (String) redisTemplate.opsForValue().get(key);
           // logger.info("paginatorCache="+paginatorCache);
           // if(!StringUtils.isEmpty(paginatorCache)){
           //     return new HttpResponseEntity(paginatorCache,HttpStatus.OK);
          //  }

            //判断如果电商服务站  则在交易详情表查交易额  否则在产品查
            if(!"2".equals(type)&&!"4".equals(type)){

                count =electricityBusinessService.getNoRegionElectricityBusinessCountByTypeByAdmin(type,addressCode);
                pagesUtil.setTotalCount(count);
                electricityBusinessDtoList=electricityBusinessService.getNoRegionElectricityBusinessListAdmin(type,addressCode,
                        pagesUtil.getStartPage(),size);
            }else{

                count = electricityBusinessService.getStoreNoRegionElectricityBusinessCountByTypeByAdmin(type,code);
                pagesUtil.setTotalCount(count);
                electricityBusinessDtoList=electricityBusinessService.getStoreNoRegionElectricityBusinessListAdmin(type,
                        code,pagesUtil.getStartPage(),size);
            }
            for (ElectricityBusinessDto electricityBusinessDto:electricityBusinessDtoList){
                if(!StringUtils.isEmpty(electricityBusinessDto.getAddressCode())){
                    String addressCodes = geoCodingsService.getAddressWhole(electricityBusinessDto.getAddressCode());
                    electricityBusinessDto.setAddressCode(addressCodes);
                }
                if(electricityBusinessDto.getMobileNo()==null||"null".equalsIgnoreCase(electricityBusinessDto.getMobileNo())){
                    electricityBusinessDto.setMobileNo("");
                }
                if(electricityBusinessDto.getResponsiblePerson()==null||"null".equalsIgnoreCase(electricityBusinessDto.getResponsiblePerson())){
                    electricityBusinessDto.setResponsiblePerson("");
                }
            }

            Paginator<List<ElectricityBusinessDto>> paginator=new Paginator<List<ElectricityBusinessDto>>(pagesUtil.getCurrentPage(),pagesUtil.getPageSize(),pagesUtil.getTotalPage(),
                    pagesUtil.getTotalCount(),electricityBusinessDtoList);
           // redisTemplate.opsForValue().set(key, JSONObject.fromObject(paginator).toString());
            return new HttpResponseEntity<Paginator<List<ElectricityBusinessDto>>>(paginator,HttpStatus.OK);
        }catch (Exception e){
            return new HttpResponseEntity(new Error().error("sql error").errorDescription(e.getMessage()),HttpStatus.SERVICE_UNAVAILABLE);
        }
    }

    @Override
    public HttpResponseEntity<Paginator<List<ElectricityBusinessDto>>> getElectricityBusinessListExceptSit(@ApiParam(value = "页码", required = true) @RequestParam(value = "start", required = true) int start, @ApiParam(value = "数据大小", required = true) @RequestParam(value = "size", required = true) int size, @ApiParam(value = "地址码", required = false) @RequestParam(value = "addressCode", required = false) String addressCode, @ApiParam(value = "开始时间", required = false) @RequestParam(value = "startTime", required = false) String startTime, @ApiParam(value = "结束时间", required = false) @RequestParam(value = "endTime", required = false) String endTime, @ApiParam(value = "电商名称", required = false) @RequestParam(value = "storeName", required = false) String storeName) {
        try {
            String code=null;
            int count=0;
            List<ElectricityBusinessDto> electricityBusinessDtoList=null;
            String orgClass = OAuth2AuthenticationImpl.ClientOrgClass();

            String clientAddressCode = electricityBusinessService.getClientAddressCode(OAuth2AuthenticationImpl.openId());
            if ("org_ebb_county".equals(orgClass)) {
                addressCode=clientAddressCode;
            }
            PagesUtil pagesUtil=new PagesUtil();
            pagesUtil.setPageSize(size);
            if(start<1){
                pagesUtil.setCurrentPage(1);
            }
            pagesUtil.setCurrentPage(start);
            if (null!=addressCode&&!"".equals(addressCode)){
                GeoCodings geoCodings=geoCodingsService.getGeoCodingsById(addressCode);
                code= SubStringUtil.separateGeoCodeByProduct(addressCode,geoCodings.getRegionLever()+1+"");
                logger.info("~~~~~~~~~~~~~~~~~~~~~~~code is:"+code);
            }

            //如果结束时间为空  则表示是TOP10页面表格数据
//            if(StringUtils.isEmpty(endTime)){
//                count =electricityBusinessService.getElectricityBusinessCount(storeName,code,startTime);
//                pagesUtil.setTotalCount(count);
//                electricityBusinessDtoList=electricityBusinessService.getElectricityBusiness( storeName,code,startTime,
//                        pagesUtil.getStartPage(),size);
//            }else{
            String key=start+"-"+size+"-"+addressCode;
            StringBuilder timeSb=new StringBuilder();
            if(!StringUtils.isEmpty(startTime)){
                timeSb.append(startTime.replace("-",""));
            }
            if(!StringUtils.isEmpty(endTime)){
                timeSb.append(endTime.replace("-",""));
            }
            key=key+timeSb.toString();
            String paginatorCache=(String) redisTemplate.opsForValue().get(key);
            if(!StringUtils.isEmpty(paginatorCache)){
                return new HttpResponseEntity(paginatorCache,HttpStatus.OK);
            }
            count =electricityBusinessService.getElectricityBusinessCountExceptSit(storeName,code,startTime,endTime);
            pagesUtil.setTotalCount(count);
            electricityBusinessDtoList=electricityBusinessService.getElectricityBusinessExceptSit( storeName,code,startTime,endTime,
                    pagesUtil.getStartPage(),size);

//            }
            for (ElectricityBusinessDto electricityBusinessDto:electricityBusinessDtoList){

                GeoCodings geoCodings = geoCodingsService.getGeoCodingsById(electricityBusinessDto.getAddressCode());
                if(null!=geoCodings&&!StringUtils.isEmpty(geoCodings.getGeoName()))
                    electricityBusinessDto.setAddressCode(geoCodings.getGeoName());
            }
            Paginator<List<ElectricityBusinessDto>> paginator=new Paginator<List<ElectricityBusinessDto>>(pagesUtil.getCurrentPage(),pagesUtil.getPageSize(),pagesUtil.getTotalPage(),
                    pagesUtil.getTotalCount(),electricityBusinessDtoList);

            redisTemplate.opsForValue().set(key, JSONObject.fromObject(paginator).toString());
            return new HttpResponseEntity<Paginator<List<ElectricityBusinessDto>>>(paginator,HttpStatus.OK);
        }catch (Exception e){
            return new HttpResponseEntity(new Error().error("sql error").errorDescription(e.getMessage()),HttpStatus.SERVICE_UNAVAILABLE);
        }

    }

    @Override
    public HttpResponseEntity<Paginator<List<ElectricityBusinessDto>>> getElectricityBusinessListFront(@ApiParam(value = "页码", required = true) @RequestParam(value = "start", required = true) int start, @ApiParam(value = "数据大小", required = true) @RequestParam(value = "size", required = true) int size, @ApiParam(value = "电商类型", required = true) @RequestParam(value = "type", required = true) String type, @ApiParam(value = "地址码", required = false) @RequestParam(value = "addressCode", required = false) String addressCode, @ApiParam(value = "电商名称", required = false) @RequestParam(value = "storeName", required = false) String storeName) {
        try {
            String code=null;
//            String orgClass = OAuth2AuthenticationImpl.ClientOrgClass();
//            String clientAddressCode = electricityBusinessService.getClientAddressCode(OAuth2AuthenticationImpl.openId());
//            if ("org_ebb_county".equals(orgClass)) {
//                addressCode=clientAddressCode;
//            }
            PagesUtil pagesUtil=new PagesUtil();
            pagesUtil.setPageSize(size);
            if(start<1){
                pagesUtil.setCurrentPage(1);
            }
            pagesUtil.setCurrentPage(start);
            if (null!=addressCode&&!"".equals(addressCode)){
                GeoCodings geoCodings=geoCodingsService.getGeoCodingsById(addressCode);
                code= SubStringUtil.separateGeoCodeByProduct(addressCode,geoCodings.getRegionLever()+1+"");
                logger.info("~~~~~~~~~~~~~~~~~~~~~~~code is:"+code);
            }
            int count =electricityBusinessService.getElectricityBusinessCountByType(type,storeName,code,null);
            pagesUtil.setTotalCount(count);
            List<ElectricityBusinessDto> electricityBusinessDtoList=electricityBusinessService.getElectricityBusinessList(type, storeName,code,null,
                    pagesUtil.getStartPage(),size);
            for (ElectricityBusinessDto electricityBusinessDto:electricityBusinessDtoList){
                String addressCodes = getAllAddress(electricityBusinessDto.getAddressCode());
                electricityBusinessDto.setAddressCode(addressCodes);
                String phone=electricityBusinessDto.getMobileNo();
                if(!StringUtils.isEmpty(phone)&&CommonUtil.isMobileNO(phone.trim())){
                    phone=  phone.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
                    electricityBusinessDto.setMobileNo(phone);
                }else if(!StringUtils.isEmpty(phone)&&CommonUtil.isLandlineNO(phone.trim())&&phone.trim().length()==12){
                    phone=  phone.replaceAll("(\\d{4})-\\w{4}(\\d{3})","$1*****$2");
                    electricityBusinessDto.setMobileNo(phone);
                }

            }
            Paginator<List<ElectricityBusinessDto>> paginator=new Paginator<List<ElectricityBusinessDto>>(pagesUtil.getCurrentPage(),pagesUtil.getPageSize(),pagesUtil.getTotalPage(),
                    pagesUtil.getTotalCount(),electricityBusinessDtoList);
            return new HttpResponseEntity<Paginator<List<ElectricityBusinessDto>>>(paginator,HttpStatus.OK);
        }catch (Exception e){
            return new HttpResponseEntity(new Error().error("sql error").errorDescription(e.getMessage()),HttpStatus.SERVICE_UNAVAILABLE);
        }
    }

    @Override
    public HttpResponseEntity<ElectricityBusinessDto> getElectricityBusiness(@ApiParam(value = "id", required = true) @RequestParam(value = "id", required = true) String id) {

        try {
            ElectricityBusinessDto electricityBusinessDto =electricityBusinessService.getElectricityBusinessById(id);
            return new HttpResponseEntity<ElectricityBusinessDto>(electricityBusinessDto,HttpStatus.OK);
        }catch (Exception e){
            return new HttpResponseEntity(new Error().error("sql error").errorDescription(e.getMessage()),HttpStatus.SERVICE_UNAVAILABLE);
        }
    }

    @Override
    public HttpResponseEntity<String> updateElectricityBusiness(@ApiParam(value = "id", required = true) @RequestBody ElectricityBusinessDto electricityBusinessDto) {
        try {
            //店铺所属区域绑定用户所属区县
            String addressCode=  electricityBusinessService.getClientAddressCode(OAuth2AuthenticationImpl.openId());
            electricityBusinessDto.setAddressCode(addressCode);
            //查询店铺url与修改前的是否一样
            int hasSameUrl=electricityBusinessService.queryElectricityBusinessUrl(electricityBusinessDto.getId(),electricityBusinessDto.getStoreUrl());
            if(hasSameUrl>0){
                electricityBusinessDto.setRemark("店铺地址已经修改，在月底自动爬取时会检测是否可以爬取");
                electricityBusinessService.updateEbbUrl(electricityBusinessDto);
            }
            int count =electricityBusinessService.updateElectricityBusiness(electricityBusinessDto);
            Set<String> keys = redisTemplate.keys("/admin/ebb/list/-" + "*");
            redisTemplate.delete(keys);
  //  /ebb/list/-
            Set<String> keys1 = redisTemplate.keys("/ebb/list/-" + "*");
            redisTemplate.delete(keys1);
            return new HttpResponseEntity<String>(count+"",HttpStatus.OK);
        }catch (Exception e){
            logger.error(e.getMessage());
            return new HttpResponseEntity(new Error().error("sql error").errorDescription(e.getMessage()),HttpStatus.SERVICE_UNAVAILABLE);
        }
    }

    @Override
    public HttpResponseEntity<String> deleteElectricityBusiness(@ApiParam(value = "id", required = true) @RequestParam(value = "id", required = true) String id) {
        try {
            int count =electricityBusinessService.deleteElectricityBusiness(id);
            //redisTemplate.delete("/admin/ebb/list/-*");
            Set<String> keys = redisTemplate.keys("/admin/ebb/list/-" + "*");
            redisTemplate.delete(keys);
            Set<String> keys1 = redisTemplate.keys("/ebb/list/-" + "*");
            redisTemplate.delete(keys1);
            return new HttpResponseEntity<String>(count+"",HttpStatus.OK);
        }catch (Exception e){
            return new HttpResponseEntity(new Error().error("sql error").errorDescription(e.getMessage()),HttpStatus.SERVICE_UNAVAILABLE);
        }
    }

    @Override
    public HttpResponseEntity<String> deleteSelectedAllElectricityBusiness(
            @ApiParam(value = "ids", required = true) @RequestBody(required = true) String ids) {
        logger.info("+++++++++++++++++===================================="+ids);
        int count = 0;
        try {
            count = electricityBusinessService.deleteSelectElectricityBusiness(ids);
            return new HttpResponseEntity<String>(count+"",HttpStatus.OK);
        }catch (Exception e){
            return new HttpResponseEntity(new Error().error("sql error").errorDescription(e.getMessage()),HttpStatus.SERVICE_UNAVAILABLE);
        }
    }

    @Override
    public HttpResponseEntity<String> insertEbbProduct(@ApiParam(value = "添加经营主体产品", required = true) @RequestBody ProductInfo productInfo) {
        productInfo.setId(UUID.randomUUID().toString());
        try {
            int count =electricityBusinessService.insertElectricityBusinessProduct(productInfo);
            return new HttpResponseEntity<String>(count+"",HttpStatus.OK);
        }catch (Exception e){
            return new HttpResponseEntity(new Error().error("sql error").errorDescription(e.getMessage()),HttpStatus.SERVICE_UNAVAILABLE);
        }
    }

    @Override
    public HttpResponseEntity<String> importLogistics(HttpServletRequest request,@RequestParam("file") MultipartFile file) {
        Error error = new Error();
        String url= request.getScheme() + "://" + host + ":" + port + "/auth/org/corp/batch/" ;
        if (file == null) {
            error.error("upload file can't be empty").errorDescription("import error");
            return new HttpResponseEntity(error, HttpStatus.MULTI_STATUS);
        }

        List<ElectricityBusiness> electricityBusinessList=readElectricityBusiness(file);
        String result =null;
        try {
            result = electricityBusinessManage.registerElectricityBusiness(electricityBusinessList,url);
            // return new HttpResponseEntity<String>(result,HttpStatus.OK);
        }catch (Exception e){
            error.error("internal server error").errorDescription(e.getMessage());
            return new HttpResponseEntity(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<String>(result,HttpStatus.OK);
    }

    /**
     * 各区域经营情况
     * @param time
     * @return
     */
    @Override
    public HttpResponseEntity<HashMap<String,Object>> platformManagementData(@ApiParam(value = "时间", required = true) @RequestParam String time) {

        String code =  "520600000000";
        HashMap<String,Object> map = new HashMap<>();

        List<Object> businessList = new ArrayList<>();//交易量
        List<Object> tradingList = new ArrayList<>();//销售量
        List<Object> addressList = new ArrayList<>();//地址

        try {
            //利用工具类生成带通配符的地址代码
            String geoCode = SubStringUtil.separateGeoCode(code,"3");
            logger.info("======================================code:" + geoCode);
            List<GeoCodings> geoCodingsList = geoCodingsService.getGeoCodingsByCode(code,geoCode);
            logger.info("======================================geoCodings:"+geoCodingsList);
            for (int i=0;i<geoCodingsList.size();i++){
                HashMap<String,Object> hashMap = electricityBusinessService.getPlatformManagement(time,geoCodingsList.get(i).getId());
                HashMap<String,Object> hashMap2 = electricityBusinessService.getPlatformManagement2(time,geoCodingsList.get(i).getId());
                if(hashMap!=null){
                    businessList.add(hashMap.get("businessVolume"));
                }else{
                    businessList.add(0);
                }
                if(hashMap2!=null){
                    tradingList.add(hashMap2.get("tradingVolume"));
                }else{
                    tradingList.add(0);
                }
                //装入地址
                addressList.add(geoCodingsList.get(i).getGeoName());
            }
            map.put("businessList",businessList);
            map.put("tradingList",tradingList);
            map.put("addressList",addressList);

//            regionManamentDtos = electricityBusinessService.getPlatformManagement(time);
//            for (RegionManamentDto regionManamentDto:regionManamentDtos){
//                GeoCodings geoCodings = geoCodingsService.getGeoCodingsById(regionManamentDto.getAddressCode());
//                if (StringUtils.isEmpty(regionManamentDto.getBusinessVolume())){
//                    regionManamentDto.setBusinessVolume("0");
//                }
//                if(StringUtils.isEmpty(regionManamentDto.getTradingVolume())){
//                    regionManamentDto.setTradingVolume("0");
//                }
//                regionManamentDto.setAddressCode(geoCodings.getGeoName());
//            }

        } catch (Exception e) {
            return new HttpResponseEntity(new Error().error("sql error").errorDescription(e.getLocalizedMessage()),HttpStatus.BAD_GATEWAY);
        }
        return new HttpResponseEntity<HashMap<String, Object>>(map,HttpStatus.OK);
    }

    //查询各区域销售额同比环比
    @Override
    public HttpResponseEntity<HashMap<String,Object>> platformSalesVolumeData(
            @ApiParam(value = "时间", required = true) @RequestParam String time
    ) {


        HashMap<String,Object> hashMap = new HashMap<>();
        try {
            Date date = new SimpleDateFormat("yyyy-MM").parse(time);
            int year=1900+date.getYear();
            String code = "520600000000";
            HashMap<String,Object> stringList = new HashMap<>();
            stringList.put("one",year+"年-0"+(date.getMonth()+1)+"月");
            stringList.put("two",year+"年-0"+(date.getMonth()+1-1)+"月");
            stringList.put("three",year+"年-0"+(date.getMonth()+1-2)+"月");

            String[] str = new String[]{"one","two","three"};
            //循环判断如果值不对则是上年
            for (int i = 0;i<str.length;i++){
                if(stringList.get(str[i]).equals(year+"年-00月")){
                    stringList.put(str[i],(year-1)+"年-12"+"月");
                }
                if(stringList.get(str[i]).equals(year+"年-0-1月")){
                    stringList.put(str[i],(year-1)+"年-11"+"月");
                }
                if(stringList.get(str[i]).equals(year+"年-0-2月")){
                    stringList.put(str[i],(year-1)+"年-10"+"月");
                }

            }
            logger.info("=================================月份:"+stringList+"\n:"+stringList.get("one"));

            //从左边开始
            List<Object> oneList = new ArrayList<>();//第一月分销售额
            List<Object> twoList = new ArrayList<>();//第二月份销售额
            List<Object> threeList = new ArrayList<>();//第三月份销售额
            List<Object> fourList = new ArrayList<>();//同比销售额
            List<Object> fiveList = new ArrayList<>();//环比销售额
            List<Object> mouthList = new ArrayList<>();//月份
            List<Object> addressList = new ArrayList<>();//地址
            //利用工具类生成带通配符的地址代码
            String geoCode = SubStringUtil.separateGeoCode(code,"3");

            logger.info("======================================code:" + geoCode);
            List<GeoCodings> geoCodingsList = geoCodingsService.getGeoCodingsByCode(code,geoCode);
            logger.info("======================================geoCodings:"+geoCodingsList);
            for (int i=0;i<geoCodingsList.size();i++){
                GeoCodings geoCodings = geoCodingsList.get(i);
                HashMap<String,Object> oneMap = electricityBusinessService.getRegionSales(geoCodings.getId(),geoCodings.Next(),
                        stringList.get(str[2]).toString().replace("年","").replace("月",""));
                HashMap<String,Object> twoMap = electricityBusinessService.getRegionSales(geoCodings.getId(),geoCodings.Next(),
                        stringList.get(str[1]).toString().replace("年","").replace("月",""));
                HashMap<String,Object> threeMap = electricityBusinessService.getRegionSales(geoCodings.getId(),geoCodings.Next(),
                        stringList.get(str[0]).toString().replace("年","").replace("月",""));
                logger.info("=========================================地址:"+geoCodings);
                if(oneMap!=null){
                    oneList.add(oneMap.get("tradingVolume"));//第一月分销售额
                }else{
                    oneList.add(0);//第一月分销售额

                }
                if(twoMap!=null){
                    twoList.add(twoMap.get("tradingVolume"));//第二月份销售额
                }else{
                    twoList.add(0);//第二月份销售额

                }
                if(threeMap!=null){
                    threeList.add(threeMap.get("tradingVolume"));//第三月份销售额
                }else{
                    threeList.add(0);//第三月份销售额
                }
                //查询去年销售额
                HashMap<String,Object> lastYearList = electricityBusinessService.getYearSales(geoCodings.getId(),geoCodings.Next(),year-1+"");
                //查询今年销售额
                HashMap<String,Object> thisYearList = electricityBusinessService.getYearSales(geoCodings.getId(),geoCodings.Next(),year+"");
                //计算同比
                if(lastYearList!=null&&thisYearList!=null){
                    logger.info("====================thisYearList:"+thisYearList.get("tradingVolume").toString());
                    double tong = thisYearList.get("tradingVolume").toString()!=null&&!thisYearList.get("tradingVolume").equals("0")?
                            Double.valueOf(lastYearList.get("tradingVolume").toString())/Double.valueOf(thisYearList.get("tradingVolume").toString()):0.0;
                    fourList.add(new DecimalFormat("#.00").format(tong));
                }else{
                    fourList.add(0.0);

                }
                //查询上个月销售额
                Date data1=new Date();
                logger.info("===============:data1"+data1.getMonth());
                HashMap<String,Object> lastMouthList = electricityBusinessService.getMouthSales(geoCodings.getId(),geoCodings.Next(),data1.getMonth()+1-1+"");
                //查询这个月销售额
                HashMap<String,Object> thisMouthList = electricityBusinessService.getMouthSales(geoCodings.getId(),geoCodings.Next(),data1.getMonth()+1+"");
                logger.info("===============:data2"+data1.getMonth());
                //计算环比
                if(lastMouthList!=null&&thisMouthList!=null) {
                    double huan = thisMouthList.get("tradingVolume").toString() != null && !thisMouthList.get("tradingVolume").equals("0") ?
                            Double.valueOf(lastMouthList.get("tradingVolume").toString()) / Double.valueOf(lastMouthList.get("tradingVolume").toString()) : 0.0;
                    fiveList.add(new DecimalFormat("#.00").format(huan));
                    logger.info("========================huan:"+new DecimalFormat("#.00").format(huan));
                }else{
                    fiveList.add(0.0);

                }
                addressList.add(geoCodings.getGeoName());

            }
            mouthList.add(stringList.get(str[2]).toString());//月份
            mouthList.add(stringList.get(str[1]).toString());//月份
            mouthList.add(stringList.get(str[0]).toString());//月份
            mouthList.add("同比");
            mouthList.add("环比");


            hashMap.put("oneList",oneList);
            hashMap.put("twoList",twoList);
            hashMap.put("threeList",threeList);
            hashMap.put("fourList",fourList);
            hashMap.put("fiveList",fiveList);
            hashMap.put("mouthList",mouthList);
            hashMap.put("addressList",addressList);
            //算出同比和环比

        } catch (Exception e) {
            return new HttpResponseEntity(
                    new Error().error("sql error").errorDescription(e.getLocalizedMessage()),HttpStatus.BAD_GATEWAY);

        }
        return new HttpResponseEntity<HashMap<String, Object>>(hashMap,HttpStatus.OK);
    }

    /**
     * 数据管理首页关联10个最新数据
     * @return
     */
    @Override
    public HttpResponseEntity<List<PlatformBusinessDto>> NewsDataGET() {
        List<PlatformBusinessDto> platformBusinessDtos = null;


        try {
            platformBusinessDtos  = electricityBusinessService.getRelationPlatform();
            for (PlatformBusinessDto platformBusinessDto :platformBusinessDtos){
                EnumCategory enumCategory = enumCategoryService.getEnumCategory(platformBusinessDto.getCategoryName());
                platformBusinessDto.setCategoryName(enumCategory.getCategoryName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new HttpResponseEntity<List<PlatformBusinessDto>>(platformBusinessDtos,HttpStatus.OK);
    }

    /**
     * 服务站点数量
     * @param addressCode
     * @return
     */
    @Override
    public HttpResponseEntity<List<RegionManamentDto>> RegisonServiceNumGET(
            @ApiParam(value = "地址码", required = true) @RequestParam String addressCode
    ) {
        List<RegionManamentDto> regionManamentDtos=null;

        try {
            GeoCodings geoCodings = geoCodingsService.getGeoCodingsById(addressCode);
            if(geoCodings.getRegionLever()<5){
                geoCodings.setRegionLever(geoCodings.getRegionLever()+1);
            }
            String code = SubStringUtil.separateGeoCode(addressCode, geoCodings.getRegionLever() + "");

            regionManamentDtos = electricityBusinessService.getServiceNumTable(code);
            for (RegionManamentDto regionManamentDto:regionManamentDtos){
                GeoCodings geoCodings1 = geoCodingsService.getGeoCodingsById(regionManamentDto.getAddressCode());
                regionManamentDto.setAddressCode(geoCodings1.getGeoName());

            }
        } catch (Exception e) {
            return new HttpResponseEntity(new Error().error("sql error").errorDescription(e.getLocalizedMessage()),HttpStatus.BAD_GATEWAY);
        }
        return new HttpResponseEntity<List<RegionManamentDto>>(regionManamentDtos,HttpStatus.OK);
    }

    /**
     * 店铺TOP10
     * @param time
     * @return
     */
    @Override
    public HttpResponseEntity<List<RegionManamentDto>> StoreTopDataGET(
            @ApiParam(value = "开始时间", required = false) @RequestParam(required = false,value = "addressCode") String addressCode,
            @ApiParam(value = "开始时间", required = false) @RequestParam(required = false) String startTime
    ) {

        List<RegionManamentDto> regionManamentDtos=null;
        try {
            regionManamentDtos = electricityBusinessService.getStoreSalesTop10(addressCode,startTime);
        } catch (Exception e) {
            return new HttpResponseEntity(new Error().error("sql error").errorDescription(e.getLocalizedMessage()),HttpStatus.BAD_GATEWAY);
        }
        return new HttpResponseEntity<List<RegionManamentDto>>(regionManamentDtos,HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<Paginator<List<RegionManamentDto>>> StoreSalesDataGET(
            @ApiParam(value = "id", required = true) @RequestParam(required = true) String id,
            @ApiParam(value = "开始页", required = true) @RequestParam(required = true) int start,
            @ApiParam(value = "页面大小", required = true) @RequestParam(required = true) int size
    ) {

        List<RegionManamentDto> regionManamentDtos = null;
        PagesUtil pagesUtil=null;
        try {
            int count = electricityBusinessService.getStoreSalesInfoCount(id);
            pagesUtil = new PagesUtil();
            pagesUtil.setPageSize(size);
            pagesUtil.setTotalCount(count);
            pagesUtil.setCurrentPage(start);
            if(start<1){
                pagesUtil.setCurrentPage(1);
            }
            regionManamentDtos = electricityBusinessService.getStoreSalesInfo(id,pagesUtil.getStartPage(),pagesUtil.getPageSize());
        } catch (Exception e) {
            return new HttpResponseEntity(new Error().error("sql error").errorDescription(e.getLocalizedMessage()),HttpStatus.BAD_GATEWAY);
        }

        return new HttpResponseEntity<Paginator<List<RegionManamentDto>>>(new Paginator<List<RegionManamentDto>>(pagesUtil.getCurrentPage(),
                pagesUtil.getPageSize(),pagesUtil.getTotalPage(),pagesUtil.getTotalCount(),regionManamentDtos),HttpStatus.OK);
    }

    /**
     * 数据统计概况
     * @return
     */
    @Override
    public HttpResponseEntity<HashMap<String, Object>> DataCountSurvey() {

        HashMap<String,Object> hashMap = new HashMap<>();

        try {
            Integer businessCount = electricityBusinessService.getBusinessCount();//平台总数
            Integer serviceCount = electricityBusinessService.getServiceCount();//服务站点总数
            Integer logisticsCount = electricityBusinessService.getLogisticsCount();//物流总数
            Integer trainCount = electricityBusinessService.getTradInfoCount();//培训总数
            Integer productCount = electricityBusinessService.getProductCount();//产品总数

            hashMap.put("businessCount",businessCount);
            hashMap.put("serviceCount",serviceCount);
            hashMap.put("logisticsCount",logisticsCount);
            hashMap.put("trainCount",trainCount);
            hashMap.put("productCount",productCount);

        } catch (Exception e) {
            return new HttpResponseEntity(new Error().error("sql error").errorDescription(e.getLocalizedMessage()),HttpStatus.BAD_GATEWAY);
        }
        return new HttpResponseEntity<HashMap<String, Object>>(hashMap,HttpStatus.OK);
    }

    /**
     * 各平台数量
     * @return
     */
    @Override
    public HttpResponseEntity<HashMap<String, Object>> getPlatformNumGET() {
        String code =  "520600000000";
        HashMap<String,Object> map = new HashMap<>();

        List<Object> platformList = new ArrayList<>();//平台数
        List<Object> addressList = new ArrayList<>();//地址

        try {
            //利用工具类生成带通配符的地址代码
            String geoCode = SubStringUtil.separateGeoCode(code,"3");
            logger.info("======================================code:" + geoCode);
            List<GeoCodings> geoCodingsList = geoCodingsService.getGeoCodingsByCode(code,geoCode);
            logger.info("======================================geoCodings:"+geoCodingsList);
            for (int i=0;i<geoCodingsList.size();i++){
                int platformCount = electricityBusinessService.getRegionPlatformCount(geoCodingsList.get(i).getId());
                platformList.add(platformCount);

                //装入地址
                addressList.add(geoCodingsList.get(i).getGeoName());
            }
            int platformCount1 = electricityBusinessService.getRegionPlatformCount("520600000000");
            platformList.add(platformCount1);
            addressList.add("无对应区县");

            map.put("platformList",platformList);
            map.put("addressList",addressList);

        } catch (Exception e) {
            return new HttpResponseEntity(new Error().error("sql error").errorDescription(e.getLocalizedMessage()),HttpStatus.BAD_GATEWAY);
        }
        return new HttpResponseEntity<HashMap<String, Object>>(map,HttpStatus.OK);
    }

    @Override
    public void exportBusiness(@ApiParam(value = "平台类型", required = true) @RequestParam(value = "type", required = true) String type,
                               @ApiParam(value = "地址编码", required = false) @RequestParam(value = "addressCode", required = false) String addressCode,
                               @ApiParam(value = "店铺名称", required = false) @RequestParam(value = "storeName", required = false) String storeName,
                               @ApiParam(value = "平台", required = false) @RequestParam(value = "platform", required = false) String platform,
                               @ApiParam(value = "时间", required = false) @RequestParam(value = "startTime",required = false) String startTime,
                               @ApiParam(value = "时间", required = false) @RequestParam(value = "endTime",required = false) String endTime,
                               HttpServletResponse response) {


        String code  = null;
        if(StringUtils.isEmpty(addressCode)&&"org_ebb_county".equals(OAuth2AuthenticationImpl.ClientOrgClass())){
            addressCode=electricityBusinessService.getClientAddressCode(OAuth2AuthenticationImpl.openId());
        }
        //获取要导出的数据
        List<ElectricityBusinessDto> electricityBusinessDtoList = new ArrayList<>();

        if (null!=addressCode&&!"".equals(addressCode)){
            GeoCodings geoCodings=geoCodingsService.getGeoCodingsById(addressCode);
            code= SubStringUtil.separateGeoCodeByProduct(addressCode,geoCodings.getRegionLever()+1+"");
            logger.info("~~~~~~~~~~~~~~~~~~~~~~~code is:"+code);
        }else{
            code=addressCode;
        }

        //判断如果电商服务站  则在交易详情表查交易额  否则在产品查
        if(!"2".equals(type)){
            electricityBusinessDtoList=electricityBusinessService.getElectricityBusinessListExort(type, storeName,code,platform,startTime,endTime);
        }else{
            electricityBusinessDtoList=electricityBusinessService.getStoreElectricityBusinessListExport(type, storeName,code,platform,startTime,endTime);

        }


//        //判断如果电商服务站  则在交易详情表查交易额  否则在产品查
//        if("2".equals(type)){
//            for(ElectricityBusinessDto electricityBusinessDto:electricityBusinessDtoList){
//                float tradingVolume = electricityBusinessService.getTradingByEleId(electricityBusinessDto.getId());
//                electricityBusinessDto.setTradingVolume(""+tradingVolume);
//                logger.info("tradingVolume:"+tradingVolume);
//            }
//        }else{
//            for(ElectricityBusinessDto electricityBusinessDto:electricityBusinessDtoList){
//                HashMap<String,Object> hashMap  = electricityBusinessService.getBusinessAndTrandingByEleId(electricityBusinessDto.getId());
//                if(hashMap!=null){
//                    electricityBusinessDto.setBusinessVolume(hashMap.get("businessVolume").toString());
//                    electricityBusinessDto.setTradingVolume(hashMap.get("tradingVolume").toString());
//                    logger.info("business:"+hashMap.get("businessVolume").toString());
//                }
//            }
//        }
        float tradingVolume = 0;
        long businessVolume = 0;
        for (ElectricityBusinessDto electricityBusinessDto:electricityBusinessDtoList){
            String addressCodes = geoCodingsService.getAddressWhole(electricityBusinessDto.getAddressCode());
            electricityBusinessDto.setAddressCode(addressCodes);
            //计算交易额和交易量
            // electricityBusinessDto.setTradingVolume(Math.round(electricityBusinessDto.getTradingVolume()));
            //electricityBusinessDto.setBusinessVolume(Math.round(electricityBusinessDto.getBusinessVolume()));
            tradingVolume +=electricityBusinessDto.getTradingVolume();//交易额
            businessVolume +=electricityBusinessDto.getBusinessVolume();//交易量
        }


        for (ElectricityBusinessDto electricityBusinessDto:electricityBusinessDtoList){
            if("1".equals(electricityBusinessDto.getType())){
                electricityBusinessDto.setType("第三方平台");
            }
            if("2".equals(electricityBusinessDto.getType())){
                electricityBusinessDto.setType("电商平台");
            }
            if("3".equals(electricityBusinessDto.getType())){
                electricityBusinessDto.setType("自建平台");
            }
        }
        String[] headers={"店铺名称","归属平台","店铺分类","地址","地址详情","负责人","联系方式","员工数","交易量","交易额","店铺网址",
                "经度","纬度","电商平台类型","交易时间"};
        String[] methods={"getStoreName","getPlatformCategory","getStoreCategory","getAddressCode","getAddressDetail",
                "getResponsiblePerson","getMobileNo","getEmployeeNum","getBusinessVolume","getTradingVolume","getStoreUrl",
                "getLongitude","getLatitude","getType","getCreateTime"};

        //将科学计算方法转成具体数字
        BigDecimal bigDecimal = new BigDecimal(businessVolume);
        BigDecimal bigDecimal2 = new BigDecimal(tradingVolume);

        ElectricityBusinessDto electricityBusinessTotalDto = new ElectricityBusinessDto();
        electricityBusinessTotalDto.setStoreName("交易量合计："+bigDecimal.toPlainString());
//        electricityBusinessTotalDto.setPlatformCategory(bigDecimal.toPlainString());
        ElectricityBusinessDto electricityBusinessTotalDto1 = new ElectricityBusinessDto();
        electricityBusinessTotalDto1.setStoreName("交易额合计："+bigDecimal2.toPlainString());
//        electricityBusinessTotalDto1.setPlatformCategory(bigDecimal2.toPlainString());

        electricityBusinessDtoList.add(electricityBusinessTotalDto);
        electricityBusinessDtoList.add(electricityBusinessTotalDto1);

        logger.info("---------------------------------:"+electricityBusinessDtoList.size());
        try {
            String filename="平台信息";
            String filepath="./"+filename;

            // filename = new String(filename.getBytes(),"iso-8859-1");

            JxlExcelUtil.writeExcelObject(filepath,headers,methods,electricityBusinessDtoList,response);

            InputStream inStream = new FileInputStream(filepath);
            response.reset();
            response.setContentType("application/msexcel;charset=UTF-8");
            //new String(("attachment;filename="+"error.xls").getBytes("GB2312")
            // filename="+new String((titlename).getBytes("gbk"),"iso8859-1")+".xls");
            response.addHeader("Content-Disposition",
                    "attachment;   filename=\"" + new String((filename).getBytes("gbk"),"iso8859-1")+ ".xls\"");
            byte[] b = new byte[100];
            int len;
            while ((len = inStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();


        } catch (Exception e) {
            logger.info(e.getMessage());
        }

    }

    @Override
    public void exportBusinessDetail(  @ApiParam(value = "类型", required = false) @RequestParam(value = "type",required = false) String type,
                                      @ApiParam(value = "开始时间", required = false) @RequestParam(value = "startTime",required = false) String startTime,
                                      @ApiParam(value = "结束时间", required = false) @RequestParam(value = "endTime",required = false) String endTime,
                                      HttpServletResponse response) {


        String orgClass=OAuth2AuthenticationImpl.ClientOrgClass();
        String clientAddressCode=null;
        // 根据电商办对应的区县 查询区县下的数据
        if("org_ebb_city".equals(orgClass)||"org_ebb_county".equals(orgClass)){
            clientAddressCode = electricityBusinessService.getClientAddressCode(OAuth2AuthenticationImpl.openId());

        }


        String[] headers={"区县","平台类型","归属平台","店铺数量","有效店铺数量","交易量","交易额"};
        String[] methods={"getAddressCode","getPlatformCategoryParent","getPlatformCategory","getStoreNumber","getProductStoreNumber",
                "getBusinessVolume","getTradingVolume1"};
//        String key=type;
//        StringBuilder timeSb=new StringBuilder();
//        if(!StringUtils.isEmpty(startTime)){
//            timeSb.append(startTime.replace("-",""));
//
//        }
//        if(!StringUtils.isEmpty(endTime)){
//            timeSb.append(endTime.replace("-",""));
//        }
//        key=key+timeSb.toString();
        List<ElectricityBusinessTotalDto> electricityBusinessTotalDtos=new ArrayList<>();

        double tradingVolume = 0;
        double businessVolume = 0;
        DecimalFormat df = new DecimalFormat("#.00");
        GeoCodings geoCodings= geoCodingsService.getGeoCodingsById(clientAddressCode);
        List<GeoCodings> geoCodingses=new ArrayList<>();
        if(null!=geoCodings&&geoCodings.getRegionLever()==2) {
            String geoCode = SubStringUtil.separateGeoCode(geoCodings.getId(), (geoCodings.getRegionLever() + 1 + ""));
            geoCodingses = geoCodingsService.getGeoCodingsByCode(geoCodings.getId(), geoCode);
            //geoCodingses.add(geoCodings);
        }//else{
        geoCodingses.add(geoCodings);
        //}
        logger.info("geoCodingses="+geoCodingses);
        for(GeoCodings geoCodings1:geoCodingses){
            List<ElectricityBusinessTotalDto> electricityBusinessTotalDtosSub0=new ArrayList<>();

            String code=geoCodingsService.getGeoCodingsById(geoCodings1.getId()).getGeoName();
            logger.info("geocode="+geoCodings1.getId()+",codeName="+geoCodings1.getGeoName());
            List<String> categorys = electricityBusinessService.getPlatformCategoryList(geoCodings1.getId(),type);
            logger.info("categorys="+categorys.toString());
            for(String category:categorys){
                List<ElectricityBusinessTotalDto> electricityBusinessTotalDtosSub=new ArrayList<>();
                ElectricityBusinessTotalDto  electricityBusinessTotalDto=new ElectricityBusinessTotalDto();
                if(!StringUtils.isEmpty(category)){
                    if("2".equals(type)){
                        electricityBusinessTotalDto = electricityBusinessService.getEbbTotalByAddressCode(geoCodings1.getId(),type,category,null,startTime,endTime);
                    }else{
                        electricityBusinessTotalDto= electricityBusinessService.getTotalByAddressCode(geoCodings1.getId(),type,category,null,startTime,endTime);
                    }
                    if(StringUtils.isEmpty(electricityBusinessTotalDto.getPlatformCategory())){
                        electricityBusinessTotalDto.setPlatformCategory(category);
                    }
                    electricityBusinessTotalDtosSub.add(electricityBusinessTotalDto);
                    logger.info("---------------------------------:"+electricityBusinessTotalDtos.size());
                    electricityBusinessTotalDtosSub0.addAll(electricityBusinessTotalDtosSub);
                }
            }

            if(electricityBusinessTotalDtosSub0!=null&&electricityBusinessTotalDtosSub0.size()>0){
                for (ElectricityBusinessTotalDto electricityBusinessTotalDto:electricityBusinessTotalDtosSub0){
                    //区县  登陆为市电商办 则包括12个区县和无对应区县（也就是 electricity_business 的地址code是 铜仁市）
                    if(geoCodings1.getId().equals("520600000000")){
                        electricityBusinessTotalDto.setAddressCode("无对应区县");
                    }else{
                        electricityBusinessTotalDto.setAddressCode(code);
                    }
                    if(electricityBusinessTotalDto!=null&&"1".equals(electricityBusinessTotalDto.getPlatformCategoryParent())){
                        electricityBusinessTotalDto.setPlatformCategoryParent("网络零售平台");
                    }else{
                        electricityBusinessTotalDto.setPlatformCategoryParent("本地生活类服务平台");
                    }
                    //店铺数量
                    int storeNumber = electricityBusinessService.getStoreNumber(geoCodings1.getId(),type,electricityBusinessTotalDto.getPlatformCategory(),null);
                    electricityBusinessTotalDto.setStoreNumber(storeNumber);
                    int ebbProductStoreNumber = electricityBusinessService.getEbbProductStoreNumber(geoCodings1.getId(),type,electricityBusinessTotalDto.getPlatformCategory(),null,startTime,endTime);
                    electricityBusinessTotalDto.setProductStoreNumber(ebbProductStoreNumber);
                    //计算交易额和交易量
                    tradingVolume +=electricityBusinessTotalDto.getTradingVolume();//交易额
                    businessVolume +=electricityBusinessTotalDto.getBusinessVolume();//交易量
                    //转成具体数字
                    BigDecimal bigDecimal = new BigDecimal(electricityBusinessTotalDto.getTradingVolume());
                    electricityBusinessTotalDto.setTradingVolume1(bigDecimal.toPlainString());

                }
            }
            electricityBusinessTotalDtos.addAll(electricityBusinessTotalDtosSub0);
        }


        logger.info("tradingVolume:"+tradingVolume);
        String format = df.format(tradingVolume);
        //将科学计算方法转成具体数字
        BigDecimal bigDecimal = new BigDecimal(businessVolume);
        BigDecimal bigDecimal2 = new BigDecimal(format);

        ElectricityBusinessTotalDto electricityBusinessTotalDto = new ElectricityBusinessTotalDto();
        electricityBusinessTotalDto.setAddressCode("交易量合计："+bigDecimal.toPlainString());
//        electricityBusinessTotalDto.setPlatformCategory(bigDecimal.toPlainString());
        ElectricityBusinessTotalDto electricityBusinessTotalDto1 = new ElectricityBusinessTotalDto();
        electricityBusinessTotalDto1.setAddressCode("交易额合计："+bigDecimal2.toPlainString());
//        electricityBusinessTotalDto1.setPlatformCategory(bigDecimal2.toPlainString());

      //  electricityBusinessTotalDtos.add(electricityBusinessTotalDto);
      //  electricityBusinessTotalDtos.add(electricityBusinessTotalDto1);


        //logger.info("electricityBusinessTotalDtos:"+electricityBusinessTotalDtos);
        try {
            String filename="分类详情表";
//            if(!StringUtils.isEmpty(addressCode)){
//                geoCodingsService.getGeoCodingsById(addressCode);
//            }

            String filepath="./"+filename;

            // filename = new String(filename.getBytes(),"iso-8859-1");

            JxlExcelUtil.writeExcelObject(filepath,headers,methods,electricityBusinessTotalDtos,response);

            InputStream inStream = new FileInputStream(filepath);
            response.reset();
            response.setContentType("application/msexcel;charset=UTF-8");
            //new String(("attachment;filename="+"error.xls").getBytes("GB2312")
            // filename="+new String((titlename).getBytes("gbk"),"iso8859-1")+".xls");
            response.addHeader("Content-Disposition",
                    "attachment;   filename=\"" + new String((filename).getBytes("gbk"),"iso8859-1")+ ".xls\"");
            byte[] b = new byte[100];
            int len;
            while ((len = inStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();


        } catch (Exception e) {
            logger.info(e.getMessage());
        }

    }

    @Override
    public void exportBusinessTotal1(@ApiParam(value = "类型", required = false) @RequestParam(value = "type", required = false) String type, @ApiParam(value = "开始时间", required = false) @RequestParam(value = "startTime", required = false) String startTime, @ApiParam(value = "结束时间", required = false) @RequestParam(value = "endTime", required = false) String endTime, HttpServletResponse response) {


        String orgClass=OAuth2AuthenticationImpl.ClientOrgClass();
        String clientAddressCode=null;
        // 根据电商办对应的区县 查询区县下的数据
        if("org_ebb_city".equals(orgClass)||"org_ebb_county".equals(orgClass)){
            clientAddressCode = electricityBusinessService.getClientAddressCode(OAuth2AuthenticationImpl.openId());

        }


        String[] headers={"区县","平台类型","店铺数量","有效店铺数量","交易量","交易额"};
        String[] methods={"getAddressCode","getPlatformCategoryParent","getStoreNumber","getProductStoreNumber",
                "getBusinessVolume","getTradingVolume1"};

        List<ElectricityBusinessTotalDto> electricityBusinessTotalDtos=new ArrayList<>();

        double tradingVolume = 0;
        double businessVolume = 0;
        double tradingVolumeWeb = 0;
        double businessVolumeWeb = 0;
        double businessVolumeLocal = 0;
        double tradingVolumeLocal = 0;
        DecimalFormat df = new DecimalFormat("#.00");
        GeoCodings geoCodings= geoCodingsService.getGeoCodingsById(clientAddressCode);
        List<GeoCodings> geoCodingses=new ArrayList<>();
        if(null!=geoCodings&&geoCodings.getRegionLever()==2) {
            String geoCode = SubStringUtil.separateGeoCode(geoCodings.getId(), (geoCodings.getRegionLever() + 1 + ""));
            geoCodingses = geoCodingsService.getGeoCodingsByCode(geoCodings.getId(), geoCode);
            //geoCodingses.add(geoCodings);
        }//else{
        geoCodingses.add(geoCodings);
        //}
        logger.info("geoCodingses="+geoCodingses);
        for(GeoCodings geoCodings1:geoCodingses){
            List<ElectricityBusinessTotalDto> electricityBusinessTotalDtosSub0=new ArrayList<>();

            String code=geoCodingsService.getGeoCodingsById(geoCodings1.getId()).getGeoName();
            logger.info("geocode="+geoCodings1.getId()+",codeName="+geoCodings1.getGeoName());
            List<String> categorys = electricityBusinessService.getPlatformCategoryList(geoCodings1.getId(),type);
            logger.info("categorys="+categorys.toString());
            //for(String category:categorys){
                List<ElectricityBusinessTotalDto> electricityBusinessTotalDtosSub=new ArrayList<>();
                ElectricityBusinessTotalDto  electricityBusinessTotalDto0=new ElectricityBusinessTotalDto();
                //if(!StringUtils.isEmpty(category)){
                    if("2".equals(type)){
                        electricityBusinessTotalDto0 = electricityBusinessService.getEbbTotalByAddressCode(geoCodings1.getId(),type,null,1,startTime,endTime);
                        electricityBusinessTotalDtosSub.add(electricityBusinessTotalDto0);
                        electricityBusinessTotalDto0 = electricityBusinessService.getEbbTotalByAddressCode(geoCodings1.getId(),type,null,2,startTime,endTime);
                        electricityBusinessTotalDtosSub.add(electricityBusinessTotalDto0);
                    }else{
                        electricityBusinessTotalDto0= electricityBusinessService.getTotalByAddressCode(geoCodings1.getId(),type,null,1,startTime,endTime);
                        electricityBusinessTotalDtosSub.add(electricityBusinessTotalDto0);
                        electricityBusinessTotalDto0= electricityBusinessService.getTotalByAddressCode(geoCodings1.getId(),type,null,2,startTime,endTime);
                        electricityBusinessTotalDtosSub.add(electricityBusinessTotalDto0);
                    }

                    logger.info("---------------------------------:"+electricityBusinessTotalDtos.size());
                    electricityBusinessTotalDtosSub0.addAll(electricityBusinessTotalDtosSub);
                //}
           // }

            if(electricityBusinessTotalDtosSub0!=null&&electricityBusinessTotalDtosSub0.size()>0){
                for (ElectricityBusinessTotalDto electricityBusinessTotalDto:electricityBusinessTotalDtosSub0){
                    //区县  登陆为市电商办 则包括12个区县和无对应区县（也就是 electricity_business 的地址code是 铜仁市）
                    if(geoCodings1.getId().equals("520600000000")){
                        electricityBusinessTotalDto.setAddressCode("无对应区县");
                    }else{
                        electricityBusinessTotalDto.setAddressCode(code);
                    }

                    //店铺数量
                    int storeNumber = electricityBusinessService.getStoreNumber(geoCodings1.getId(),type,null,electricityBusinessTotalDto.getPlatformCategoryParent());
                    electricityBusinessTotalDto.setStoreNumber(storeNumber);
                    int ebbProductStoreNumber = electricityBusinessService.getEbbProductStoreNumber(geoCodings1.getId(),type,null,electricityBusinessTotalDto.getPlatformCategoryParent(),startTime,endTime);
                    electricityBusinessTotalDto.setProductStoreNumber(ebbProductStoreNumber);
                    //计算交易额和交易量
                    tradingVolume +=electricityBusinessTotalDto.getTradingVolume();//交易额
                    businessVolume +=electricityBusinessTotalDto.getBusinessVolume();//交易量
                    if("1".equals(electricityBusinessTotalDto.getPlatformCategoryParent())){
                        electricityBusinessTotalDto.setPlatformCategoryParent("网络零售平台");
                        tradingVolumeWeb+=electricityBusinessTotalDto.getTradingVolume();
                        businessVolumeWeb+=electricityBusinessTotalDto.getBusinessVolume();
                    }
                    if("2".equals(electricityBusinessTotalDto.getPlatformCategoryParent())||StringUtils.isEmpty(electricityBusinessTotalDto.getPlatformCategoryParent())){
                        electricityBusinessTotalDto.setPlatformCategoryParent("本地生活类服务平台");
                        tradingVolumeLocal+=electricityBusinessTotalDto.getTradingVolume();
                        businessVolumeLocal+=electricityBusinessTotalDto.getBusinessVolume();
                    }
                    //转成具体数字
                    BigDecimal bigDecimal = new BigDecimal(electricityBusinessTotalDto.getTradingVolume());
                    electricityBusinessTotalDto.setTradingVolume1(bigDecimal.toPlainString());

                }
            }
            electricityBusinessTotalDtos.addAll(electricityBusinessTotalDtosSub0);
        }


        logger.info("tradingVolume:"+tradingVolume);
        String format = df.format(tradingVolume);
        //将科学计算方法转成具体数字
        BigDecimal bigDecimal = new BigDecimal(businessVolume);
        BigDecimal bigDecimal2 = new BigDecimal(format);

        String formatWeb = df.format(tradingVolumeWeb);
        //将科学计算方法转成具体数字
        BigDecimal bigDecimalBusinessWeb = new BigDecimal(businessVolumeWeb);
        BigDecimal bigDecimalTradingWeb = new BigDecimal(formatWeb);

        String formatLocal = df.format(tradingVolumeLocal);
        //将科学计算方法转成具体数字
        BigDecimal bigDecimalBusinessLocal = new BigDecimal(businessVolumeLocal);
        BigDecimal bigDecimalTradingLocal = new BigDecimal(formatLocal);

        ElectricityBusinessTotalDto electricityBusinessTotalDtoWeb = new ElectricityBusinessTotalDto();
        electricityBusinessTotalDtoWeb.setAddressCode("网络零售平台交易量合计："+bigDecimalBusinessWeb.toPlainString());
        ElectricityBusinessTotalDto electricityTradingTotalDtoWeb = new ElectricityBusinessTotalDto();
        electricityTradingTotalDtoWeb.setAddressCode("网络零售平台交易额合计："+bigDecimalTradingWeb.toPlainString());

        ElectricityBusinessTotalDto electricityBusinessTotalDtoLocal = new ElectricityBusinessTotalDto();
        electricityBusinessTotalDtoLocal.setAddressCode("本地生活类服务平台交易量合计："+bigDecimalBusinessLocal.toPlainString());
        ElectricityBusinessTotalDto electricityTradingTotalDtoLocal = new ElectricityBusinessTotalDto();
        electricityTradingTotalDtoLocal.setAddressCode("本地生活类服务平台交易额合计："+bigDecimalTradingLocal.toPlainString());

        ElectricityBusinessTotalDto electricityBusinessTotalDto = new ElectricityBusinessTotalDto();
        electricityBusinessTotalDto.setAddressCode("交易量合计："+bigDecimal.toPlainString());
        ElectricityBusinessTotalDto electricityBusinessTotalDto1 = new ElectricityBusinessTotalDto();
        electricityBusinessTotalDto1.setAddressCode("交易额合计："+bigDecimal2.toPlainString());

        electricityBusinessTotalDtos.add(electricityBusinessTotalDtoWeb);
        electricityBusinessTotalDtos.add(electricityTradingTotalDtoWeb);
        electricityBusinessTotalDtos.add(electricityBusinessTotalDtoLocal);
        electricityBusinessTotalDtos.add(electricityTradingTotalDtoLocal);

        electricityBusinessTotalDtos.add(electricityBusinessTotalDto);
        electricityBusinessTotalDtos.add(electricityBusinessTotalDto1);


        try {
            String filename="汇总表";
//            if(!StringUtils.isEmpty(addressCode)){
//                geoCodingsService.getGeoCodingsById(addressCode);
//            }

            String filepath="./"+filename;

            // filename = new String(filename.getBytes(),"iso-8859-1");

            JxlExcelUtil.writeExcelObject(filepath,headers,methods,electricityBusinessTotalDtos,response);

            InputStream inStream = new FileInputStream(filepath);
            response.reset();
            response.setContentType("application/msexcel;charset=UTF-8");
            //new String(("attachment;filename="+"error.xls").getBytes("GB2312")
            // filename="+new String((titlename).getBytes("gbk"),"iso8859-1")+".xls");
            response.addHeader("Content-Disposition",
                    "attachment;   filename=\"" + new String((filename).getBytes("gbk"),"iso8859-1")+ ".xls\"");
            byte[] b = new byte[100];
            int len;
            while ((len = inStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();


        } catch (Exception e) {
            logger.info(e.getMessage());
        }

    }

    @Override
    public HttpResponseEntity<List<String>> platformCategoryGET(@ApiParam(value = "平台类型", required = false) @RequestParam(value = "type",required = false) String type) {

        List<String> list = electricityBusinessService.getPlatformCategoryList(null,type);
        return new HttpResponseEntity<List<String>>(list,HttpStatus.OK);

    }

    private List readElectricityBusiness(MultipartFile multipartFile){
        List<ElectricityBusiness> electricityBusinessList=new ArrayList<>();
        try {
            //打开文件
            Workbook book = Workbook.getWorkbook(multipartFile.getInputStream());
            //取得第一个sheet
            Sheet sheet = book.getSheet(0);

            //取得行数
            int rows = sheet.getRows();

            for (int i = 2; i < rows; i++) {
                Cell[] cell = sheet.getRow(i);
                for (int j = 0; j < cell.length; j++) {
                    System.out.println(cell[j].getContents());
                }
                ElectricityBusiness electricityBusiness = new ElectricityBusiness();
                //经营主体id
                electricityBusiness.setId(UUID.randomUUID().toString());



                //店铺名称
                String storeName = sheet.getCell(0, i).getContents();
                if (!StringUtils.isEmpty(storeName)&&!"null".equals(storeName)) {
                    electricityBusiness.setStoreName(storeName);
                }

                //归属平台
                String platformCategory = sheet.getCell(1, i).getContents();
                if (!StringUtils.isEmpty(platformCategory)&&!"null".equals(platformCategory)) {
                    electricityBusiness.setPlatformCategory(platformCategory);
                }

                //店铺分类
                String storeCategory = sheet.getCell(2,i).getContents();
                try{
                    if(!StringUtils.isEmpty(storeCategory)){
                        List<EnumCategory> categories = enumCategoryService.getCategoryByName(storeCategory);
                        if (categories.size() > 0) {
                            electricityBusiness.setStoreCategoryId(categories.get(0).getId());
                        }else {
                            electricityBusiness.setStoreCategoryId("130000000013");
                        }
                    }

                }catch (Exception e){
                    electricityBusiness.setStoreCategoryId("130000000013");
                }


                //地址码
                String addressCode = sheet.getCell(3, i).getContents();
                if (!StringUtils.isEmpty(addressCode)&&!"null".equals(addressCode)) {
                    addressCode=   JxlExcelUtil.geoMap.get(addressCode.trim());
                    electricityBusiness.setAddressCode(addressCode);
                }

                //地址详情
                String addressDetail = sheet.getCell(4, i).getContents();
                if (!StringUtils.isEmpty(addressDetail)&&!"null".equals(addressDetail)) {
                    electricityBusiness.setAddressDetail(addressDetail);
                }

                //负责人
                String responsiblePerson = sheet.getCell(5, i).getContents();
                if (!StringUtils.isEmpty(responsiblePerson)&&!"null".equals(responsiblePerson)) {
                    electricityBusiness.setResponsiblePerson(responsiblePerson);
                }

                //联系方式
                String mobileNo = sheet.getCell(6, i).getContents();
                if (!StringUtils.isEmpty(mobileNo)&&!StringUtils.isEmpty(mobileNo.trim())&&!"null".equals(mobileNo.trim())) {
                    electricityBusiness.setMobileNo(mobileNo.trim());
                }

                //员工数
                String employeeNum = sheet.getCell(7, i).getContents().trim();
                if (!StringUtils.isEmpty(employeeNum)&&!"null".equals(employeeNum)) {
                    electricityBusiness.setEmployeeNum(Integer.parseInt(employeeNum));
                }


                //经度
                String  longitude=sheet.getCell(8,i).getContents();
                if (!StringUtils.isEmpty(longitude)&&!"null".equals(longitude)){
                    electricityBusiness.setLongitude(longitude);
                }
                //纬度
                String  latitude=sheet.getCell(9,i).getContents();
                if (!StringUtils.isEmpty(latitude)&&!"null".equals(latitude)){
                    electricityBusiness.setLatitude(latitude);
                }
                //平台类型
                String  type=sheet.getCell(10,i).getContents();
                if(!StringUtils.isEmpty(type)&&!"null".equals(type)){
                    if ("第三方平台".equals(type)){
                        electricityBusiness.setType("1");
                        //店铺网址
                        String storeUrl = sheet.getCell(11, i).getContents();
                        if (!StringUtils.isEmpty(storeUrl)&&!"null".equals(storeUrl)) {
                            electricityBusiness.setStoreUrl(storeUrl);
                        }
                    }else if("电商站点".equals(type)){
                        electricityBusiness.setType("2");
                        electricityBusiness.setStoreUrl("");
                    }else if("自建平台".equals(type)){
                        electricityBusiness.setType("3");
                        //店铺网址
                        String storeUrl = sheet.getCell(11, i).getContents();
                        if (!StringUtils.isEmpty(storeUrl)&&!"null".equals(storeUrl)) {
                            electricityBusiness.setStoreUrl(storeUrl);
                        }
                    }
                }else if("电商企业".equals(type)){
                    electricityBusiness.setType("4");
                    //店铺网址
                    String storeUrl = sheet.getCell(11, i).getContents();
                    if (!StringUtils.isEmpty(storeUrl)&&!"null".equals(storeUrl)) {
                        electricityBusiness.setStoreUrl(storeUrl);
                    }
                }
//                //月交易量
//                String businessVolume=sheet.getCell(12,i).getContents();
//                if(!StringUtils.isEmpty(businessVolume)){
//                    electricityBusiness.setBusinessVolume(businessVolume);
//                }
//                //月交易量单位
//                String unit=sheet.getCell(13,i).getContents();
//                if(!StringUtils.isEmpty(unit)){
//                    electricityBusiness.setUnit(unit);
//                }
//                //交易额
//                String tradingVolume=sheet.getCell(14,i).getContents();
//                if(!StringUtils.isEmpty(tradingVolume)){
//                    electricityBusiness.setTradingVolume(tradingVolume);
//                }
//                //交易时间
//                String tradingTime=sheet.getCell(15,i).getContents();
//                if(!StringUtils.isEmpty(tradingTime)){
//                    electricityBusiness.setTradingTime(tradingTime);
//                }
                if(!StringUtils.isEmpty(electricityBusiness.getStoreName())){
                    electricityBusinessList.add(electricityBusiness);
                }

            }
            //关闭文件
            book.close();
        } catch (BiffException e) {
            logger.error("数据读取出错！", e);
        } catch (IOException e) {
            logger.error("数据读取出错！", e);
        }
        return  electricityBusinessList;
    }






    private String getAllAddress(String addressCode) {
        String farmAdress="";
        if(StringUtils.isEmpty(addressCode)||addressCode.length()<12){
            return null;
        }
        Map<String,String> geoCodingsMap= CommonUtil.parseGeoCodings(addressCode);
        String  city=geoCodingsService.getGeoCodingsById(geoCodingsMap.get("city"))==null?"":geoCodingsService.getGeoCodingsById(geoCodingsMap.get("city")).getGeoName();
        String  county=geoCodingsService.getGeoCodingsById(geoCodingsMap.get("county"))==null?"":geoCodingsService.getGeoCodingsById(geoCodingsMap.get("county")).getGeoName();
        String  vilage=geoCodingsService.getGeoCodingsById(geoCodingsMap.get("vilage"))==null?"":geoCodingsService.getGeoCodingsById(geoCodingsMap.get("vilage")).getGeoName();
        String  burg=geoCodingsService.getGeoCodingsById(geoCodingsMap.get("burg"))==null?"":geoCodingsService.getGeoCodingsById(geoCodingsMap.get("burg")).getGeoName();
        if(!StringUtils.isEmpty(city)){
            farmAdress+=city;
        }
        if(!StringUtils.isEmpty(county)){
            farmAdress+=county;
        }
        if(!StringUtils.isEmpty(vilage)){
            farmAdress+=vilage;
        }
        if(!StringUtils.isEmpty(burg)){
            farmAdress+=burg;
        }
        return farmAdress;
    }
    /**
     * 将一个字符串表示的地址准换为地址对象
     *
     * @param text 字符串表示的地址
     * @return
     */
    private Address convertAddress(String text) {
        //构建一个正则表达式
        StringBuilder regExp = new StringBuilder();
        regExp.append("([\u4e00-\u9fa5\\w]+?[省]||.)");
        regExp.append("([\u4e00-\u9fa5\\w]+?[市]||.)");
        regExp.append("([\u4e00-\u9fa5\\w]+?[区县]||.)");
        regExp.append("([\u4e00-\u9fa5\\w]+?[乡镇]||.)");
        regExp.append("([\u4e00-\u9fa5\\w]+?[居村委会]||.)");

        Pattern pattern = Pattern.compile(regExp.toString());
        Matcher matcher = pattern.matcher(text);
        Address address = new Address();
        if (matcher.find()) {
            address.setProvence(matcher.group(1));
            address.setCity(matcher.group(2));
            address.setCounty(matcher.group(3));
            address.setVillage(matcher.group(4));
            address.setBurg(matcher.group(5));
        }
        return address;
    }


//    public static void main(String args[] ) throws ParseException {
//        Date date = new SimpleDateFormat("yyyy-MM").parse("2016-03");
//
//        System.out.print(Double.valueOf("null"));
//    }
}
